import React, { useState } from 'react';
import { Form, Input, Button, Select, message } from 'antd';
import { UserOutlined, LockOutlined, MailOutlined } from '@ant-design/icons';
import { useHistory } from 'react-router-dom';
import api from '../services/api';

const { Option } = Select;

const RegisterPage = () => {
  const [loading, setLoading] = useState(false);
  const history = useHistory();

  const onFinish = async (values) => {
    setLoading(true);
    try {
      const response = await api.post('/auth/register', values);
      console.log('注册成功:', response.data);
      message.success('注册成功');
      // 跳转到登录页
      history.push('/login');
    } catch (error) {
      console.error('注册失败:', error);
      if (error.response) {
        // 服务器响应了错误
        const errorMessage = error.response.data?.detail || '注册失败，请稍后重试';
        message.error(errorMessage);
      } else if (error.request) {
        // 请求发出但没有收到响应
        message.error('网络错误，请检查网络连接');
      } else {
        // 其他错误
        message.error('注册失败，请稍后重试');
      }
    } finally {
      setLoading(false);
    }
  };

  return (
    <div style={{ maxWidth: 300, margin: '50px auto' }}>
      <h2 style={{ textAlign: 'center', marginBottom: 30 }}>用户注册</h2>
      <Form
        name="register"
        onFinish={onFinish}
      >
        <Form.Item
          name="username"
          rules={[{ required: true, message: '请输入用户名!' }]}
        >
          <Input prefix={<UserOutlined className="site-form-item-icon" />} placeholder="用户名" />
        </Form.Item>
        
        <Form.Item
          name="email"
          rules={[
            { required: true, message: '请输入邮箱!' },
            { type: 'email', message: '请输入有效的邮箱地址!' }
          ]}
        >
          <Input prefix={<MailOutlined className="site-form-item-icon" />} placeholder="邮箱" />
        </Form.Item>
        
        <Form.Item
          name="password"
          rules={[
            { required: true, message: '请输入密码!' },
            { min: 6, message: '密码至少6位!' }
          ]}
        >
          <Input.Password prefix={<LockOutlined className="site-form-item-icon" />} placeholder="密码" />
        </Form.Item>
        
        <Form.Item
          name="role"
          rules={[{ required: true, message: '请选择角色!' }]}
        >
          <Select placeholder="选择角色">
            <Option value="customer">客户</Option>
            <Option value="engineer">工程师</Option>
            <Option value="admin">管理员</Option>
          </Select>
        </Form.Item>
        
        <Form.Item>
          <Button type="primary" htmlType="submit" loading={loading} block>
            注册
          </Button>
          已有账户？<a href="/login">立即登录!</a>
        </Form.Item>
      </Form>
    </div>
  );
};

export default RegisterPage;